package me.pinion.controller;

import me.pinion.Log;
import me.pinion.check.annotation.AllowMethod;
import me.pinion.check.annotation.CheckRunTime;
import me.pinion.controller.annotation.RouteBind;
import me.pinion.model.Attach;
import me.pinion.oss.BucketKit;
import me.pinion.service.AttachService;

import java.io.*;

@RouteBind("/attach")
public class AttachController extends Controller{

    AttachService attachService;

    public void index(){
        try{
            Attach attach = Attach.dao.findById(getParaToInt(0));
            renderJson(attach);
        }catch (NumberFormatException e){
            Log.e(e);
            renderError(400);
        }
    }

    public void dis() throws IOException {
        Attach attach = Attach.dao.findById(getParaToInt(0));
        redirect(BucketKit.getURL(attach.getStr("url")));
    }

    @AllowMethod({"POST"})
    @CheckRunTime
    public void save() throws IOException{
        renderJson(attachService.saveAttach(this));
    }

    public void imageUp(){
        if (getRequest().getMethod().equals("GET")){
            renderText("updateSavePath( [\"/attach/imageUp\"] );", "text/javascript");
        }else if (getRequest().getMethod().equals("POST")){
            Attach attach = attachService.saveAttach(this, "upfile");
            File file = attach.getFile();
            renderJson("{'original':'"+file.getName()+"','url':'/attach/dis/"+attach.getInt("id")+"','title':'"+file.getName()+"','state':'SUCCESS'}");
        }
    }

    public void fileUp(){
        if (getRequest().getMethod().equals("GET")){
            renderText("updateSavePath( [\"/attach/imageUp\"] );", "text/javascript");
        }else if (getRequest().getMethod().equals("POST")){
            Attach attach = attachService.saveAttach(this, "upfile");
            File file = attach.getFile();
            renderJson("{'original':'"+file.getName()+"','url':'/attach/dis/"+attach.getInt("id")+"','title':'"+file.getName()+"','state':'SUCCESS'}");
        }
    }
}
